import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:carousel_slider_plus/carousel_slider_plus.dart';
import 'package:ecy_app_flutter/routes/blind_box/blind_box_list.dart';
import 'package:ecy_app_flutter/routes/blind_box/category_image_selector.dart';
import 'package:ecy_app_flutter/routes/blind_box/exchange_market/EcyExchangeMarketPage.dart';
import 'package:ecy_app_flutter/routes/blind_box/exchange_market/models/blind_box_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ecy_app_flutter/EcyRouter.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../ecycommon/utils/EcyLogger.dart';
import '../../../model/EcyApiCommonPage.dart';
import '../../../model/EcyApiCommonResponse.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../goods/model/CommodityTop.dart';

class BlindBoxMultiChoose extends StatefulWidget {
  const BlindBoxMultiChoose({super.key,required this.commodityPageList});
  final List<BlindBoxPageMore> commodityPageList;

  @override
  State<BlindBoxMultiChoose> createState() => _BlindBoxMultiChooseState();
}

class _BlindBoxMultiChooseState extends State<BlindBoxMultiChoose> {
  _BlindBoxMultiChooseState();

  final RefreshController _refreshControllerFirst = RefreshController(initialRefresh: false);
  final RefreshController _refreshControllerSec = RefreshController(initialRefresh: false);

  int _currentPage = 1;
  bool _hasMore = false;
  String _selectedPaymentMethod = 'alipay'; // 默认选中支付宝

  final List<int> indexList = List.filled(19, 0);
  final List<CommodityTop> _commodityTopList = [];

  // 新增：模拟图片、已买、选中等数据
  final List<String> imgList = [
    'https://picsum.photos/400/600?image=10',
    'https://picsum.photos/400/600?image=20',
    'https://picsum.photos/400/600?image=30',
    'https://picsum.photos/400/600?image=40',
    'https://picsum.photos/400/600?image=50',
    'https://picsum.photos/400/600?image=60',
    'https://picsum.photos/400/600?image=70',
    'https://picsum.photos/400/600?image=80',
    'https://picsum.photos/400/600?image=90',
    'https://picsum.photos/400/600?image=100',
    'https://picsum.photos/400/600?image=110',
    'https://picsum.photos/400/600?image=120',
  ];
  List<bool> isBought = [false, true, false, false, true, false, false, false, false, false, false, false, false];
  List<bool> isSelected = List.filled(13, false);
  double pricePerItem = 15.0;

  bool showCustomDialog = false;
  @override
  void initState() {
    super.initState();
    _refreshData("");
    // 页面加载后自动弹出弹窗
    WidgetsBinding.instance.addPostFrameCallback((_) {
      showDialog(
        context: context,
        barrierDismissible: false, // 不允许点击遮罩关闭
        builder: (context) => Dialog(
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: _buildMultiSelectGrid(),
          ),
        ),
      );
    });
  }

  //无数据时下拉刷新
  Future<void> _onRefresh1() async {
    _currentPage = 1;
    await _refreshData("");
    // 重置上拉加载状态
    _refreshControllerFirst.refreshCompleted();
  }

  //下拉刷新
  Future<void> _onRefresh2() async {
    _currentPage = 1;
    await _refreshData("");
    _refreshControllerSec.refreshCompleted();
    // 重置上拉加载状态
    if (_hasMore) {
      _refreshControllerSec.loadComplete();
    } else {
      _refreshControllerSec.loadNoData();
    }
  }

  //上拉加载更多
  Future<void> _onLoading2() async {
    if (_hasMore) {
      _currentPage++;
      await _refreshData("");
      _refreshControllerSec.loadComplete();
    } else {
      _refreshControllerSec.loadNoData();
    }
  }

  Future<void> _refreshData(String search) async {
    try {
      Map<String, dynamic> body = {
        "pageIndex": _currentPage,
        "pageSize": 2,
        "search": search,
      };
      var response = await EcyRequestbasemanager().get("/app/api/app/top/top", body);
      if (response != null) {
        var commonResponse = EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EcyApiCommonPage<BlindBoxPageMore> commonPage =
              EcyApiCommonPage.fromJson(response["data"], (json) => BlindBoxPageMore.fromJson(json));
          _hasMore = (commonPage.pages ?? 0) > _currentPage;
          _currentPage = commonPage.current ?? 0;
          var commodityPageList = commonPage.records ?? [];
          if (_currentPage == 1) {
           widget.commodityPageList.clear();
          }
          setState(() {
            widget.commodityPageList.addAll(commodityPageList);
          });
        }
      }
    } catch (e) {
      EcyLogger.log("获取盲抽失败$e");
    }
  }

  @override
  Widget build(BuildContext context) {
    int _selectedCount = isSelected.where((e) => e).length;
    double _totalPrice = _selectedCount * pricePerItem;
    return Scaffold(
      backgroundColor: const Color(0XFFF5F5F5),
      appBar: AppBar(
        title: Text('盲抽选择', style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w700, color: Colors.black)),
        centerTitle: true,
        backgroundColor: Colors.white,
        elevation: 0,
        iconTheme: IconThemeData(color: Colors.black),
      ),
      bottomNavigationBar: !showCustomDialog ? _buildSettlementBar() : null,
      body: Container(), // 主体内容留空
    );
  }

  Widget avatar = Image.asset('assets/images/login_app_icon.png', width: 70.w, height: 70.h, fit: BoxFit.cover);
  
  Card _buildPayCard() {
    return Card(
      margin: EdgeInsets.all(0),
      elevation: 0,
      color: Color(0xFFF5F5F5),
      child: Padding(
        padding: EdgeInsets.all(10.w),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Image.asset('assets/images/pay/icon_confirm_zfb.png', width: 22.w, height: 22.h, fit: BoxFit.cover),
                    SizedBox(width: 8.w),
                    Text("支付宝", style: TextStyle(fontSize: 14, color: Color(0xFF262626)),),
                  ],
                ),
                Radio<String>(
                  value: 'alipay',
                  groupValue: _selectedPaymentMethod,
                  onChanged: (value) {
                    setState(() {
                      _selectedPaymentMethod = value!;
                    });
                  },
                  activeColor: Color(0xFFEA4B9B),
                ),
              ],
            ),
            SizedBox(height: 10.h),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Image.asset('assets/images/pay/icon_confirm_wx.png', width: 22.w, height: 22.h, fit: BoxFit.cover),
                    SizedBox(width: 8.w),
                    Text("微信", style: TextStyle(fontSize: 14, color: Color(0xFF262626)),),
                  ],
                ),
                Radio<String>(
                  value: 'wechat',
                  groupValue: _selectedPaymentMethod,
                  onChanged: (value) {
                    setState(() {
                      _selectedPaymentMethod = value!;
                    });
                  },
                  activeColor: Color(0xFFEA4B9B),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
  Card _buildShouldKnowCard() {
    return Card(
      elevation: 0,
      color: Color(0xFFFFFFFF),
      child: Column(
        children: [
          Text('请注意', style: TextStyle(fontSize: 12, color: Color(0xFF8C8C8C)),),
          Text('请注意', style: TextStyle(fontSize: 12, color: Color(0xFF8C8C8C)),),
          Text('请注意', style: TextStyle(fontSize: 12, color: Color(0xFF8C8C8C)),),
        ],
      ),
    );
  }
 

  Widget _buildMultiSelectGrid() {
    int itemsPerRow = 4;
    int rowCount = (imgList.length / itemsPerRow).ceil();
    List<Widget> rows = [];
    for (int row = 0; row < rowCount; row++) {
      int start = row * itemsPerRow;
      int end = (start + itemsPerRow > imgList.length) ? imgList.length : start + itemsPerRow;
      rows.add(
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: List.generate(end - start, (i) {
            int index = start + i;
            bool bought = isBought[index];
            bool selected = isSelected[index];
            return GestureDetector(
              onTap: bought
                  ? null
                  : () {
                      setState(() {
                        isSelected[index] = !isSelected[index];
                      });
                    },
              child: Container(
                margin: EdgeInsets.all(2),
                width: 40,
                height: 40,
                decoration: BoxDecoration(
                  color: bought
                      ? Colors.grey[200]
                      : (selected ? Colors.pinkAccent.withOpacity(0.2) : Colors.white),
                  border: Border.all(
                    color: selected ? Colors.pink : Colors.grey[300]!,
                    width: selected ? 2 : 1,
                  ),
                  // borderRadius: BorderRadius.circular(8),
                ),
                child: Stack(
                  children: [
                    Center(
                      child: bought
                          ? Icon(Icons.block, color: Colors.grey, size: 20)
                          : Image.network(imgList[index], fit: BoxFit.cover, width: 40, height: 40),
                    ),
                    if (selected)
                      Positioned(
                        right: 2,
                        top: 2,
                        child: Icon(Icons.check_circle, color: Colors.pink, size: 16),
                      ),
                  ],
                ),
              ),
            );
          }),
        ),
      );
    }
    return Container(
      padding: EdgeInsets.all(2),
      color: Colors.white,
      child: Column(
        children: rows,
      ),
    );
  }

  Widget _buildSettlementBar() {
    int selectedCount = isSelected.where((e) => e).length;
    double total = selectedCount * pricePerItem;
    bool allSelectableSelected = isSelected
        .asMap()
        .entries
        .where((e) => !isBought[e.key])
        .every((e) => e.value);
    return Container(
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
      child: Row(
        children: [
          Checkbox(
            value: allSelectableSelected,
            onChanged: (val) {
              setState(() {
                for (int i = 0; i < isSelected.length; i++) {
                  if (!isBought[i]) isSelected[i] = val ?? false;
                }
              });
            },
          ),
          Text('全选'),
          Spacer(),
          Text('合计: ￥${total.toStringAsFixed(2)}'),
          SizedBox(width: 12),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.pinkAccent,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
            ),
            onPressed: selectedCount == 0 ? null : _showDialog,
            child: Text('去结算($selectedCount)'),
          ),
        ],
      ),
    );
  }

  void _showDialog() {
    setState(() {
      showCustomDialog = true;
    });
  }

  void _hideDialog() {
    setState(() {
      showCustomDialog = false;
    });
  }

  @override
  void dispose() {
    _refreshControllerFirst.dispose();
    _refreshControllerSec.dispose();
    super.dispose();
  }
}
